#include "LineParser.h"

#include "LineDescGroupParser.h"
#include "DoubleParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

LineParser::LineParser(
    DoubleParser *&_startXParser
    , DoubleParser *&_startYParser
    , DoubleParser *&_endXParser
    , DoubleParser *&_endYParser
    , LineDescGroupParser *&_lineDescGroupParser
):    m_startXParser(_startXParser)
    , m_startYParser(_startYParser)
    , m_endXParser(_endXParser)
    , m_endYParser(_endYParser)
    , m_lineDescGroupParser(_lineDescGroupParser)
{

}

bool LineParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Line());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("startX")))
    {
        data = reader->attributes().value(QStringLiteral("startX"));
        if (!m_startXParser->parse(reader, data))
            return false;
        m_result->startX = m_startXParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("startX: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("startY")))
    {
        data = reader->attributes().value(QStringLiteral("startY"));
        if (!m_startYParser->parse(reader, data))
            return false;
        m_result->startY = m_startYParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("startY: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("endX")))
    {
        data = reader->attributes().value(QStringLiteral("endX"));
        if (!m_endXParser->parse(reader, data))
            return false;
        m_result->endX = m_endXParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("endX: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("endY")))
    {
        data = reader->attributes().value(QStringLiteral("endY"));
        if (!m_endYParser->parse(reader, data))
            return false;
        m_result->endY = m_endYParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("endY: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (m_lineDescGroupParser->isSubstitution(name))
        {
            if (!m_lineDescGroupParser->parse(reader))
                return false;
            auto result = m_lineDescGroupParser->result();
            m_result->lineDescGroup = result;
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Line *LineParser::result()
{
    return m_result.take();
}

}